/**
 * 异步任务队列处理
 */
const TaskSync = function() {
  this._taskList = []
  this._excutorList = []
}

/**
 * 添加异步任务
 * @param {Promise<any>} taskPromise 异步任务
 */
TaskSync.prototype.add = function(taskPromise) {
  const task = {
    resolve: (res) => {
      this._taskList.pop()
      const excutor = this._excutorList.pop()
      if (excutor) {
        excutor(null, res)
      }
    },
    reject: (err) => {
      this._taskList.pop()
      const excutor = this._excutorList.pop()
      if (excutor) {
        excutor(err)
      }
    }
  }
  taskPromise.then(task.resolve).catch(task.reject)
  this._taskList.push(task)
  return this
}

/**
 * 在异步任务执行完成之后调用excutor
 * @param {() => Promise<any>} excutor excutor
 */
TaskSync.prototype.next = function(excutor) {
  this._excutorList.push(excutor)
  return this
}

exports.TaskSync = TaskSync